import axios, { AxiosResponse, AxiosError } from 'axios';
import { User, InterestTag } from '../store/slices/userSlice';
import { Activity } from '../store/slices/activitySlice';
import { Notification, Chat } from '../store/slices/messageSlice';

export const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:5000';

// 设置 Axios 的默认 baseURL - 移除或注释掉此行，以便使用相对路径，依赖 CRA 代理
// axios.defaults.baseURL = API_BASE_URL;

const api = axios.create({
    // baseURL: API_BASE_URL, // 如果上面注释了默认 baseURL，这里也通常不需要设置
    headers: {
        'Content-Type': 'application/json',
    },
});

// 添加响应拦截器
api.interceptors.response.use(
    (response: AxiosResponse) => response,
    (error: AxiosError) => {
        // 确保错误对象包含完整的响应信息
        if (error.response) {
            // 服务器返回了错误状态码
            return Promise.reject({
                response: {
                    data: error.response.data,
                    status: error.response.status
                }
            });
        } else if (error.request) {
            // 请求已发出但没有收到响应
            return Promise.reject({
                response: {
                    data: { message: '服务器无响应，请稍后重试' }
                }
            });
        } else {
            // 请求配置出错
            return Promise.reject({
                response: {
                    data: { message: '请求配置错误' }
                }
            });
        }
    }
);

// 为文件上传配置一个单独的 axios 实例（可选但很有用）
const uploadApi = axios.create({
    baseURL: API_BASE_URL,
    headers: {
        'Content-Type': 'multipart/form-data', // 为 form data 设置内容类型
    },
});

interface Tag {
    id: number;
    name: string;
}

// 实际的 API 函数（使用我们刚刚创建的后端）
const auth = {
    login: async (username: string, password: string): Promise<{ success: boolean, user?: User, token?: string, message?: string }> => {
        try {
            // 请求路径改回 /api/auth/login
            const response: AxiosResponse = await api.post('/api/auth/login', { username, password });
            return response.data;
        } catch (error: AxiosError | any) {
            // 从错误响应中获取后端返回的消息
            const errorMessage = error.response?.data?.message || '登录失败，请重试';
            return { success: false, message: errorMessage };
        }
    },

    register: async (username: string, email: string, password: string, gender?: string, avatar?: string): Promise<{ success: boolean, message?: string }> => {
        try {
            // 请求路径改回 /api/auth/register
            const response: AxiosResponse = await api.post('/api/auth/register', { username, email, password, gender, avatar });
            return response.data;
        } catch (error: AxiosError | any) {
            return { success: false, message: error.response?.data?.message || 'Registration failed' };
        }
    },

    // 新增: 获取用户资料
    getUserProfile: async (token: string): Promise<{ success: boolean, user?: User, message?: string }> => {
        try {
            // 请求路径改回 /api/auth/me
            const response: AxiosResponse = await api.get('/api/auth/me', {
                headers: { Authorization: `Bearer ${token}` },
            });
            return response.data;
        } catch (error: AxiosError | any) {
            return { success: false, message: error.response?.data?.message || 'Failed to fetch user profile' };
        }
    },

    // 新增: 更新用户资料
    updateUserProfile: async (token: string, userData: Partial<Omit<User, 'interestTags'>> & { interestTags?: number[] }): Promise<{ success: boolean, user?: User, message?: string }> => {
        try {
            // 请求路径改回 /api/auth/me
            const response: AxiosResponse = await api.put('/api/auth/me', userData, {
                headers: { Authorization: `Bearer ${token}` },
            });
            return response.data;
        } catch (error: AxiosError | any) {
            return { success: false, message: error.response?.data?.message || 'Failed to update user profile' };
        }
    },
};

// 新增: 上传相关 API 调用
const upload = {
    uploadAvatar: async (formData: FormData): Promise<{ success: boolean, url?: string, message?: string }> => {
        try {
            // 请求路径改回 /api/upload/avatar
            const response = await api.post('/api/upload/avatar', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });
            return response.data;
        } catch (error: any) {
            console.error('Upload API error:', error);
            return { success: false, message: error.response?.data?.message || 'File upload failed' };
        }
    },
    // 如果需要，在此处添加其他上传相关的 API 调用
};

const activityApi = {
    // 示例: 获取活动列表
    fetchActivities: async (): Promise<{ success: boolean, data?: Activity[], message?: string }> => {
        try {
            // 请求路径改回 /api/activities
            const response: AxiosResponse = await api.get('/api/activities');
            return response.data;
        } catch (error: AxiosError | any) {
            return { success: false, message: error.response?.data?.message || 'Failed to fetch activities' };
        }
    },
    // 示例: 创建活动
    createActivity: async (activityData: Partial<Activity>): Promise<{ success: boolean, data?: Activity, message?: string }> => {
        try {
            const response: AxiosResponse = await api.post('/activities', activityData);
            return response.data;
        } catch (error: AxiosError | any) {
            return { success: false, message: error.response?.data?.message || 'Failed to create activity' };
        }
    },
    // 在此处添加其他活动相关的 API 调用
};

const messageApi = {
    // 示例: 获取通知
    fetchNotifications: async (): Promise<{ success: boolean, data?: Notification[], message?: string }> => {
        try {
            // 请求路径改回 /api/notifications
            const response: AxiosResponse = await api.get('/api/notifications');
            return response.data;
        } catch (error: AxiosError | any) {
            return { success: false, message: error.response?.data?.message || 'Failed to fetch notifications' };
        }
    },
    // 示例: 获取聊天记录
    fetchChats: async (): Promise<{ success: boolean, data?: Chat[], message?: string }> => {
        try {
            const response: AxiosResponse = await api.get('/chats');
            return response.data;
        } catch (error: AxiosError | any) {
            return { success: false, message: error.response?.data?.message || 'Failed to fetch chats' };
        }
    },
    // 在此处添加其他消息相关的 API 调用
};

const tags = {
    getAllTags: async (): Promise<{ success: boolean, tags?: InterestTag[], message?: string }> => {
        try {
            // 请求路径改回 /api/tags
            const response: AxiosResponse = await api.get('/api/tags');
            return response.data;
        } catch (error: AxiosError | any) {
            return { success: false, message: error.response?.data?.message || 'Failed to fetch tags' };
        }
    },
};

// 新增圈子相关的 API 调用
const circleApi = {
    fetchCircles: async (): Promise<{ success: boolean, circles?: any[], message?: string }> => {
        try {
            // 请求路径改回 /api/circles
            const response: AxiosResponse = await api.get('/api/circles');
            return response.data;
        } catch (error: AxiosError | any) {
            return { success: false, message: error.response?.data?.message || '加载圈子列表失败' };
        }
    },
    // 在此处添加其他圈子相关的 API 调用，例如获取圈子详情、成员、帖子等
};

// 导出分组的 API
export default {
    auth,
    tags,
    upload,
    activity: activityApi,
    message: messageApi,
    circles: circleApi,
}; 